package com.yaohj.web.config;

import lombok.val;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.charset.StandardCharsets;

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedissonConfig {

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient(RedisProperties redisProperties) {
        Config config = new Config();
        // 集群配置
        config.useClusterServers()
                .addNodeAddress(redisProperties.getCluster().getNodes().stream()
                        .map(node -> "redis://" + node)
                        .toArray(String[]::new))
                .setPassword(redisProperties.getPassword())  // 设置密码
                .setTimeout(3000);  // 超时时间（毫秒）

        // 使用Jackson序列化器解决中文问题
        config.setCodec(new StringCodec(StandardCharsets.UTF_8));
        return Redisson.create(config);
    }
}
